<?php

namespace App\Kuafu\Order\Service;

use App\Kuafu\Pay\Model\PayStreamModel;

class OrderDb
{
    const DB_TYPE_ORDER  = 1; // 堂食
    const DB_TYPE_WAIMAI = 2; // 外卖
    const DB_TYPE_PAY    = 3; // 支付

    const DN_CONNETCTIONS = [
        self::DB_TYPE_ORDER  => 'mysqlOrder',
        self::DB_TYPE_PAY    => 'mysqlOrder',
        self::DB_TYPE_WAIMAI => 'mysqlWaiMai',
    ];

    // 单库取模规则
    const PER_MOD = 100000;

    /**
     * 获取 订单分表表名
     *
     * @param int|null $shopId
     * @param int $dbType
     * @param int $sysType
     * @return string
     * @throws \Exception
     */
    public static function orderDbConnection(?int $shopId, int $dbType = self::DB_TYPE_ORDER, int $sysType = 0): string
    {
        if (floor($shopId / self::PER_MOD) > 1) {
            throw new \Exception('门店 ID 超出最大数据库上限 ' . (self::PER_MOD * 2) . ', 请检查后再试', 0);
        }

        $dnConnection = self::DN_CONNETCTIONS[$dbType];

        switch ($dbType) {
            case self::DB_TYPE_ORDER:
            case self::DB_TYPE_WAIMAI:
                $dnConnection = self::setDnConnect($shopId, $dnConnection);

                break;
            case self::DB_TYPE_PAY:
                if (in_array($sysType, PayStreamModel::SYS_TYPE_PAY_IN_APP)) {
                    $dnConnection = self::setDnConnect($shopId, $dnConnection);
                }
        }

        return $dnConnection;
    }

    // connection+后缀
    private static function setDnConnect(?int $shopId, string $dnConnection): string
    {
        if ($shopId >= self::PER_MOD) {
            $dnConnection .= '_' . (floor($shopId / self::PER_MOD) + 1);

            return $dnConnection;
        }

        return $dnConnection;
    }
}
